package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

func initChan(c chan int) {
	for i := 1; i <= 1000; i++ {
		c <- i
	}
	close(c)
	wg.Done()
}

func primeChan(c chan int, e chan int, p chan bool) {
	for v := range c {
		var flag bool = true
		for i := 2; i < v; i++ {
			if v%i == 0 {
				flag = false
				break
			}
		}
		if flag {
			e <- v
		}
	}
	p <- true
	wg.Done()
}

func printPrime(e chan int) {
	for v := range e {
		fmt.Printf("%v是素数\n", v)
	}
	wg.Done()
}

func main() {
	// 创建存储管道
	ch := make(chan int, 1000)
	// 存放素数的管道
	em := make(chan int, 10000)
	// 存放协程 的管道
	pn := make(chan bool, 16)

	wg.Add(1)
	go initChan(ch)

	for i := 1; i <= cap(pn); i++ {
		wg.Add(1)
		go primeChan(ch, em, pn)
	}

	wg.Add(1)
	go printPrime(em)

	wg.Add(1)
	go (func() {
		for i := 0; i < cap(pn); i++ {
			<-pn
		}
		close(pn)
		close(em)
		wg.Done()
	})()

	wg.Wait()
	fmt.Println("执行结束....")
}
